<?php 

if( !defined('CORE_PATH')) die("Access Denied");

class FeedbackManager extends Manager {
	
	protected $models = array('Feedback', 'FeedbackCategory','Site');
	
	public function __construct() {
		parent::__construct('feedback','feedback_categories');
		$this->setItemClassName('Feedback');
		$this->setCategoryClassName('FeedbackCategory');
	}
	
	/**
	 * Adds a feedback record from the client
	 *
	 * @param string $catTag the tag used for the category
	 * @param string $name the name of the front end user
	 *
	 */
	public function addFeedback($catTag, $name, $email, $phone, $subject, $message) {
		
		// database reference
		$db = $this->getDatabase();
		
		// if the message has already been sent, then abort the send
		if( isset($_GET['message_sent']) ) return;
		
		// the id of the category by its tage
		$cat = $this->getCategoryByTag($catTag);
		
		if( $cat == NULL ) {
			trigger_error("Feedback Category Not Specified. Process Cancelled");
			return;
		}
		
        $feedback = new Feedback( array(
            "CategoryID" => $cat->getId(),
            "Name" => $name,
            "Email" => $email,
            "Phone_Number" => $phone,
            "Subject" => $subject,
            "Message" => $message,
            "Date_Posted" => date("Y-m-d"),
            "Status" => "unread"
        ));

        $feedback->save();
		
		// indicate the message has been sent so it is not saved twice.
		$_GET['message_sent'] = "true";
		
		// attempt to send an email to the specified Forward Email Address.
		$query = sprintf("SELECT fc.*, s.SiteName, s.SiteEmail FROM {$this->FeedbackCategory->getTableName()} fc "
			   . "INNER JOIN {$this->Site->getTableName()} s ON s.id = fc.SiteID WHERE fc.id = %s",
			   $db->sanitizeInput($cat->getId(),'int'));
			   
		$row_rsCatInfo = $db->query($query)->getRow();
		
		$feedCat = $row_rsCatInfo['CategoryName'];
		$fwdToEmail = $row_rsCatInfo['FwdToEmail'];
		$siteEmail = $row_rsCatInfo['SiteEmail'];
		$siteName = $row_rsCatInfo['SiteName'];
		
		if( $fwdToEmail == "true" ) {
			
			// define to whom we are sending the mail
			$to = "" . $row_rsCatInfo['FwdEmail'];
			$fwd_message = "This message was posted by <b>$name</b>, with the address <b>$email</b> on " 
						 . date("d/m/Y H:i") . "<br /><br />" . $message;
			
			// check if the site has defined an email address and use that as the
			// sender address, else use the user's email address.
			$from = $siteEmail != "" ? $siteEmail : $email;
			
			$this->sendMessage( array(
				'to' => $to,
				'subject' => $subject,
				'from' => $from,
				'message' => $fwd_message
			));
		}
	}
	
	/**
	 * Returns the ID of the category with the specified tag
	 *
	 * @return FeedbackCategory the database record ID of the category with the specified tag
	 */
	public function getCategoryByTag($tag) {
		$categories = $this->find( $this->getCategoryClassName(), array(
            'filter' => array("CategoryTag" => $tag, "SiteID" => SITE_ID )
        ));
		
        return $categories[0];
	}
	
	/**
	 * Returns an array containing the database records of the Feedback Categories
	 * 
	 * @return array an array of database records
	 */
	public function getFeedbackCategories($site = NULL) {
        if( $site == NULL && defined('SITE_ID') ) {
            $site = SITE_ID;
        }

        return $this->getCategories( array(
            'filter' => array("SiteID" => $site),
            'order' => array('CategoryName ASC')
        ));
		
	}
	
	
	public function sendMessage($params = array()) {
		global $site;
		
		$senderName = $site->getSiteName();
		$to = $from = $subject = $message = NULL;
		
		if( count($params) == 0 ) {
			return;	
		}
		
		if( !isset($params['to']) ) {
			trigger_error("Receipts Email Address Must Be Specified");
			return;	
		} else {
			$to = $params['to'];	
		}
		
		if( !isset($params['message']) ) {
			trigger_error("No message has been specified. Email cannot be sent.");
			return;	
		} else {
			$message = $params['message'];	
		}
		
		if( isset($params['subject']) ) {
			$subject = $params['subject'];
		} else {
			$subject = "Message From " . $params['to'];
		}
		
		if( isset($params['from']) ) {
			$from = $params['from'];
		} else {
			$from = $site->getSiteEmail();
		}
		
		$headers  = "MIME-Version: 1.0\r\n"; 
		$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
		$headers .= "To:  <" . $to . ">\r\n"; 
		$headers .= "From: {$senderName} <".$from.">\r\n";
		
		$isLocalhost = $_SERVER['HTTP_HOST'] == "localhost" ? true : false;
		
		if( !$isLocalhost ) {
			@mail($to,$subject,$message, $headers);
		}
	}
}


?>